Introduction to Wrapper Classes in Java
Course: Core Java Training
Topic: Introduction to Wrapper Classes in Java
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Wrapper Classes
Java is an object-oriented programming language, but it supports eight primitive data types that are not objects. These primitive types include int, char, boolean, double, and others. Sometimes, Java programs need to represent primitive values as objects, such as when working with collections, generic classes, or APIs that require object references.
Wrapper classes are classes that represent primitive values as objects. Each of Java's eight primitive data types has a corresponding wrapper class. For example, Integer wraps an int value, while Double wraps a double value.
Wrapper classes also provide useful methods for converting values, parsing strings, comparing numbers, and working with primitive data.
2. Learning Objectives
- Understand the meaning and purpose of wrapper classes.
- Identify all eight primitive types and their wrapper classes.
- Learn boxing, unboxing, autoboxing, and auto-unboxing.
- Convert primitive values and strings using wrapper-class methods.
- Understand how wrapper classes are used with collections and generics.
- Recognize common errors and performance considerations.
3. Primitive Data Types and Their Wrapper Classes
Java provides eight primitive data types. Each has a corresponding wrapper class in the java.lang package, which is imported automatically.
| Primitive Type |
Wrapper Class |
Example |
byte |
Byte |
Byte value = 10; |
short |
Short |
Short value = 100; |
int |
Integer |
Integer value = 1000; |
long |
Long |
Long value = 10000L; |
float |
Float |
Float value = 10.5f; |
double |
Double |
Double value = 99.99; |
char |
Character |
Character value = 'A'; |
boolean |
Boolean |
Boolean value = true; |
Remember that the wrapper class names are not always formed by simply capitalizing the primitive type. For example, int maps to Integer, and char maps to Character.
4. Why Do We Need Wrapper Classes?
4.1 Working with Collections
Java collections such as ArrayList and HashSet store objects, not primitive values directly. Wrapper classes allow primitive data to be used in these collections.
import java.util.ArrayList;
public class WrapperCollectionExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
System.out.println(numbers);
}
}
Output:
[10, 20, 30]
Here, Integer is used as the collection's element type. Java automatically converts the primitive integer literals into Integer objects through autoboxing.
4.2 Supporting Generics
Java generics work with reference types. For example, ArrayList<Integer> is valid, while ArrayList<int> is not valid. Wrapper classes make primitive values compatible with generic classes and methods.
4.3 Providing Utility Methods
Wrapper classes contain methods for parsing strings, converting values, comparing numbers, and obtaining textual representations. For example, Integer.parseInt() converts a numeric string into an int.
4.4 Representing the Absence of a Value
A primitive variable cannot hold null, but a wrapper-class reference can. This can be useful when a value is optional, such as a database field that has not been supplied.
Integer age = null; // Allowed
// int age = null; // Compilation error
A nullable wrapper must be checked before unboxing; otherwise, a NullPointerException can occur.
5. Boxing and Unboxing
5.1 Boxing
Boxing is the process of converting a primitive value into its corresponding wrapper object.
int number = 25;
Integer wrappedNumber = Integer.valueOf(number);
System.out.println(wrappedNumber);
Output:
25
The method Integer.valueOf() returns an Integer object representing the specified integer value.
5.2 Unboxing
Unboxing is the process of extracting a primitive value from its wrapper object.
Integer wrappedNumber = Integer.valueOf(50);
int number = wrappedNumber.intValue();
System.out.println(number);
Output:
50
The intValue() method extracts the primitive int value from an Integer object.
6. Autoboxing and Auto-Unboxing
6.1 Autoboxing
Autoboxing is Java's automatic conversion of a primitive value into its corresponding wrapper object. It reduces the need to call methods such as Integer.valueOf() manually.
public class AutoboxingExample {
public static void main(String[] args) {
int number = 100;
Integer object = number;
System.out.println(object);
}
}
Output:
100
6.2 Auto-Unboxing
Auto-unboxing is Java's automatic conversion of a wrapper object into its corresponding primitive value.
public class AutoUnboxingExample {
public static void main(String[] args) {
Integer object = 200;
int number = object;
System.out.println(number);
}
}
Output:
200
6.3 Comparison
| Feature |
Boxing |
Unboxing |
| Meaning |
Primitive to wrapper object |
Wrapper object to primitive |
| Example |
Integer x = 10; |
int x = wrapper; |
| Automatic form |
Autoboxing |
Auto-unboxing |
| Potential concern |
Object creation or reuse and overhead |
Null references can cause exceptions |
7. Converting Strings to Primitive Values
Wrapper classes provide parsing methods for converting text into primitive values. These methods are useful when reading user input, processing files, or handling configuration values.
public class ParsingExample {
public static void main(String[] args) {
int age = Integer.parseInt("25");
double price = Double.parseDouble("149.50");
boolean active = Boolean.parseBoolean("true");
long population = Long.parseLong("500000");
System.out.println(age);
System.out.println(price);
System.out.println(active);
System.out.println(population);
}
}
Output:
25
149.5
true
500000
Important points:
Integer.parseInt() returns a primitive int.
Double.parseDouble() returns a primitive double.
Long.parseLong() returns a primitive long.
Boolean.parseBoolean() returns true only when the string equals "true", ignoring case; other strings return false.
- Invalid numeric text generally causes a
NumberFormatException.
8. Converting Strings into Wrapper Objects
If an object is required rather than a primitive, use methods such as Integer.valueOf() or Double.valueOf().
public class WrapperConversionExample {
public static void main(String[] args) {
Integer quantity = Integer.valueOf("120");
Double rating = Double.valueOf("4.8");
System.out.println(quantity);
System.out.println(rating);
}
}
Output:
120
4.8
Use parseXxx() methods when a primitive is needed and valueOf() when a wrapper object is needed. Java may reuse some wrapper instances, so programs should not depend on receiving a newly allocated object every time.
9. Useful Methods of Wrapper Classes
| Method |
Description |
Example |
Integer.parseInt(String) |
Converts numeric text into a primitive integer. |
Integer.parseInt("42") |
Integer.valueOf(String) |
Returns an Integer representing numeric text. |
Integer.valueOf("42") |
Integer.toString() |
Converts an integer object to text. |
Integer.valueOf(42).toString() |
Integer.compare(a, b) |
Compares two primitive integer values. |
Integer.compare(5, 8) |
Integer.max(a, b) |
Returns the greater integer value. |
Integer.max(5, 8) |
Integer.min(a, b) |
Returns the smaller integer value. |
Integer.min(5, 8) |
Character.isDigit(ch) |
Checks whether a character is a digit. |
Character.isDigit('7') |
Character.isLetter(ch) |
Checks whether a character is a letter. |
Character.isLetter('A') |
Double.parseDouble(text) |
Parses text as a primitive double. |
Double.parseDouble("2.5") |
Wrapper classes are in java.lang, so they do not require explicit import statements.
10. Constants and Numeric Limits
Numeric wrapper classes provide constants that describe supported values.
public class WrapperConstantsExample {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Double.MAX_VALUE);
System.out.println(Byte.MIN_VALUE);
}
}
These constants are useful when validating input or understanding the limits of numeric data types. For example, an integer outside the range of Integer.MIN_VALUE through Integer.MAX_VALUE cannot be represented as an ordinary Java int.
11. Comparing Wrapper Objects
Wrapper classes are objects, so it is important to understand the difference between value comparison and reference comparison.
11.1 Using equals()
The equals() method checks whether two wrapper objects represent equal values of the same wrapper type.
Integer first = Integer.valueOf(1000);
Integer second = Integer.valueOf(1000);
System.out.println(first.equals(second));
Output:
true
11.2 Using ==
For wrapper objects, == checks whether two references point to the same object. It should not generally be used to compare wrapper values.
Integer first = Integer.valueOf(1000);
Integer second = Integer.valueOf(1000);
System.out.println(first == second);
The result is not a reliable value comparison; it may be false because the references may point to different objects. Some wrapper values, particularly small integer values, may be cached, so == can appear to work in limited cases. Use equals() for object value comparison or compare unboxed primitive values when appropriate.
12. Wrapper Classes Are Immutable
Wrapper classes are immutable, meaning that the value represented by a wrapper object cannot be changed after the object has been created. An operation that appears to update a wrapper variable instead assigns a different wrapper value to that variable.
Integer number = 10;
number = number + 5;
System.out.println(number);
Output:
15
The original Integer object is not modified. Java unboxes the value for addition and then boxes the result for assignment.
13. Primitive Types vs Wrapper Classes
| Feature |
Primitive Type |
Wrapper Class |
| Example |
int |
Integer |
| Category |
Primitive value |
Reference type |
| Can hold null |
No |
Yes |
| Usable as generic type argument |
No |
Yes |
| Has object methods |
No |
Yes |
| Typical performance |
Usually lower overhead |
May have object and boxing overhead |
| Example declaration |
int count = 10; |
Integer count = 10; |
14. Common Mistakes and Troubleshooting
14.1 Unboxing a Null Reference
Integer number = null;
int value = number; // Throws NullPointerException
Solution: Check that the wrapper is not null before unboxing it.
Integer number = null;
int value = number != null ? number : 0;
14.2 Parsing Invalid Numeric Text
int value = Integer.parseInt("hello");
This throws NumberFormatException because the text is not a valid integer representation.
Solution: Validate input and handle parsing errors with a suitable try-catch block.
try {
int value = Integer.parseInt("123");
System.out.println(value);
} catch (NumberFormatException exception) {
System.out.println("Please enter a valid integer.");
}
14.3 Comparing Objects with ==
Using == for wrapper values can produce unexpected results because it compares object identity. Use equals() for value comparison, taking care to handle possible null values.
14.4 Using Wrappers Unnecessarily in Performance-Critical Code
Frequent boxing and unboxing can introduce overhead in intensive loops. Prefer primitives for ordinary numeric calculations unless object behavior, collections, or nullable values are required.
14.5 Confusing parseXxx() and valueOf()
Integer.parseInt("10") returns an int, while Integer.valueOf("10") returns an Integer. Choose the method based on the type needed by the program.
15. Best Practices for Using Wrapper Classes
- Use primitive types for routine calculations when nullable or object behavior is not needed.
- Use wrapper classes when working with collections, generics, or APIs that require objects.
- Use
equals() instead of == when comparing wrapper object values.
- Check for
null before unboxing a wrapper reference.
- Validate user input before parsing numeric strings.
- Use
parseXxx() for primitive results and valueOf() for wrapper results.
- Avoid unnecessary wrapper creation and repeated boxing in performance-sensitive code.
- Remember that wrapper objects are immutable.
```html
16. Practical Example: Student Marks Management
This example demonstrates how wrapper classes can be used to store student marks, handle missing values, calculate averages, and work with collections.
import java.util.ArrayList;
import java.util.List;
public class StudentMarksExample {
public static void main(String[] args) {
List<Integer> marks = new ArrayList<>();
marks.add(85);
marks.add(90);
marks.add(78);
marks.add(95);
int total = 0;
for (Integer mark : marks) {
total += mark;
}
double average = (double) total / marks.size();
System.out.println("Marks: " + marks);
System.out.println("Total: " + total);
System.out.println("Average: " + average);
}
}
Output:
Marks: [85, 90, 78, 95]
Total: 348
Average: 87.0
Explanation:
- The
List<Integer> stores marks as wrapper objects.
- Each integer literal is automatically converted to an
Integer through autoboxing.
- The enhanced
for loop retrieves each wrapper value.
- The addition operation automatically unboxes each
Integer into an int.
- The total is divided by the number of marks to calculate the average.
17. Wrapper Classes and the Number Class
The numeric wrapper classes Byte, Short, Integer, Long, Float, and Double extend the abstract Number class. This class provides methods for converting a numeric object into different primitive numeric types.
public class NumberClassExample {
public static void main(String[] args) {
Number value = Integer.valueOf(120);
System.out.println(value.intValue());
System.out.println(value.doubleValue());
System.out.println(value.longValue());
}
}
Output:
120
120.0
120
The Number reference can refer to different numeric wrapper objects. However, Character and Boolean do not extend Number.
18. Important Points About Wrapper Classes
- All eight wrapper classes belong to the
java.lang package.
- Wrapper objects are immutable.
- Wrapper references can hold
null, but primitive variables cannot.
- Autoboxing and unboxing were introduced in Java 5.
- Generic collections use wrapper types instead of primitive types.
- Use
Integer.parseInt() to convert a numeric string into an int.
- Use
Integer.valueOf() when an Integer object is required.
- Use
equals() to compare wrapper values rather than relying on ==.
- Unboxing a null wrapper reference causes a
NullPointerException.
- Wrapper classes provide useful constants, parsing methods, conversion methods, and comparison methods.
19. Practice Exercises
Exercise 1: Identify Wrapper Classes
Write the wrapper class corresponding to each primitive type: int, char, double, boolean, and long.
Exercise 2: Demonstrate Autoboxing
Create an int variable, assign it to an Integer variable, and print the result.
Exercise 3: Demonstrate Unboxing
Create an Integer object, assign it to an int variable, and display the primitive value.
Exercise 4: Convert String Values
Convert "250" into an integer and "45.75" into a double. Print both values.
Exercise 5: Use Wrapper Classes with Collections
Create an ArrayList<Integer>, insert five numbers, and calculate their sum and average.
Exercise 6: Handle Invalid Input
Attempt to parse the text "Java123" as an integer. Use a try-catch block to handle the resulting NumberFormatException.
Exercise 7: Compare Wrapper Objects
Create two separate Integer references with the same numeric value. Compare them using both equals() and ==, and explain the difference.
20. Interview Questions and Answers
Q1. What is a wrapper class in Java?
A wrapper class represents a primitive data type as an object. For example, Integer represents int, and Character represents char.
Q2. Why are wrapper classes required?
They allow primitive values to be used where objects are required, such as in generic collections, and provide useful methods for conversion and comparison.
Q3. Name all eight wrapper classes.
Byte, Short, Integer, Long, Float, Double, Character, and Boolean.
Q4. What is autoboxing?
Autoboxing is the automatic conversion of a primitive value into its corresponding wrapper object. For example, Integer number = 10;.
Q5. What is unboxing?
Unboxing is the automatic conversion of a wrapper object into its corresponding primitive value. For example, int number = Integer.valueOf(10);.
Q6. What is the difference between parseInt() and valueOf()?
Integer.parseInt("25") returns a primitive int, whereas Integer.valueOf("25") returns an Integer object.
Q7. Can wrapper objects contain null?
Yes. A wrapper reference can contain null. However, attempting to unbox a null reference throws a NullPointerException.
Q8. Are wrapper classes mutable?
No. Wrapper classes are immutable. Their represented values cannot be changed after an object is created.
Q9. Why can we not use int in ArrayList<int>?
Java generics require reference types, not primitive types. Use ArrayList<Integer> instead.
Q10. What is the difference between == and equals() for wrappers?
== compares object references, while equals() compares represented values for wrapper classes. For value comparison, prefer equals() or compare safely unboxed primitives.
Q11. What happens when an invalid number is parsed?
Methods such as Integer.parseInt() throw NumberFormatException when the supplied text is not a valid integer representation.
Q12. Do wrapper classes require an import statement?
No. They are part of the java.lang package, which Java makes available automatically.
21. Quick Revision Checklist
- Understand the meaning and purpose of wrapper classes.
- Memorize the mapping between primitive types and wrapper classes.
- Understand boxing, unboxing, autoboxing, and auto-unboxing.
- Know when to use
parseXxx() and valueOf().
- Understand why wrapper classes work with collections and generics.
- Remember that wrapper objects are immutable.
- Handle null values before unboxing.
- Use
equals() for wrapper value comparison.
- Handle invalid numeric strings appropriately.
- Practice writing small Java programs using wrapper classes.
22. Conclusion
Wrapper classes are an important part of Core Java because they allow primitive values to be represented as objects. They make it possible to work with collections and generics, handle nullable values, and use convenient conversion and comparison methods. Understanding the eight wrapper classes, boxing, unboxing, and common pitfalls will help you write more reliable Java programs and prepare for technical interviews.
To learn more about Java programming, explore the JustAcademy Core Java Training Course. You can also register for a course demo or visit the JustAcademy website.